package com.hmjk.health.health;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.ADose;
import com.hmjk.health.util.ADrugReminder;
import com.hmjk.health.util.AReminder;
import com.hmjk.health.util.ReminderList;
import com.hmjk.health.util.reminderTime;
import com.hmjk.health.views.SwitchButton;
import com.hmjk.health.views.SwitchButton.OnChangeListener;

import android.app.Activity;
//import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
//import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

public class HealthDrugReminderEdit extends Activity implements OnClickListener{
	private final String TAG = HealthDrugReminderEdit.class.getSimpleName();
	private HealthApp mApp = null;
	
	private String tid = "", terminaltype="";
	private int index = 0;
	private ADrugReminder reminder = null;
	private ReminderList mReminderList = null;
	private List<ADose> doseList = new ArrayList<ADose>();
	
	private LinearLayout mDoseList = null;
	private TextView reminderTime = null;
	private SwitchButton mSwitchButton = null;
	private TextView mSun = null, mMon = null, mTue = null, mWed = null, mThur = null, mFri = null, mSat = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		mApp = (HealthApp) getApplication();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.health_drug_reminder_edit);
		
        Intent i = getIntent();
        tid = i.getStringExtra("tid");
        index = i.getIntExtra("index", 0);
        terminaltype = i.getStringExtra("terminaltype");
        
        ImageButton butBack = (ImageButton)findViewById(R.id.back);
		butBack.setOnClickListener(this);
		TextView butAdd = (TextView)findViewById(R.id.drug_add_but);
		butAdd.setText("+" + " " + " " + getResources().getString(R.string.reminder_add));
		butAdd.setOnClickListener(this);
        
        mReminderList = new ReminderList();
        mDoseList = (LinearLayout)findViewById(R.id.drug_list);
        
        reminderTime = (TextView)findViewById(R.id.time);
        reminderTime.setOnClickListener(this);
        mSwitchButton = (SwitchButton)findViewById(R.id.switch_but);
        mSwitchButton.setOnChangeListener(new OnChangeListener() {
			
			@Override
			public void onChange(SwitchButton sb, boolean state) {
				// TODO Auto-generated method stub
				
			}
		});
        
        mSun = (TextView)findViewById(R.id.but_sun);
        mSun.setOnClickListener(this);
        mMon = (TextView)findViewById(R.id.but_mon);
        mMon.setOnClickListener(this);
        mTue = (TextView)findViewById(R.id.but_tue);
        mTue.setOnClickListener(this);
        mWed = (TextView)findViewById(R.id.but_wed);
        mWed.setOnClickListener(this);
        mThur = (TextView)findViewById(R.id.but_thur);
        mThur.setOnClickListener(this);
        mFri = (TextView)findViewById(R.id.but_fri);
        mFri.setOnClickListener(this);
        mSat = (TextView)findViewById(R.id.but_sat);
        mSat.setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		mApp.initDoseChooseList();
		retreiveReminderList();
		retreiveDoseList();
		updateViews();
	}
	
	private void retreiveReminderList(){
		mReminderList.cleanReminder();
		
		String[] args = new String[1];
		args[0] = new String(tid);
		mReminderList = (ReminderList)mApp.getDataManager().checkData(DataManager.F_DRUG_REMINDER, args);

	}
	
	private void retreiveDoseList(){
		int size = mReminderList.length();
		doseList.clear();
		reminder = null;
		if(size > 0){
			for(AReminder d:mReminderList.getReminderList()){
				ADrugReminder rem = (ADrugReminder)d;
				if(tid.equalsIgnoreCase(rem.tid) && (index == rem.Index)){
					reminder = rem;
					String doseListString = rem.getDoseListJSONArrayStr();
					try {
						JSONArray arr = new JSONArray(doseListString);
						
						if(arr.length() > 0){
							for(int j = 0;j<arr.length();j++){
								JSONObject json = arr.getJSONObject(j);
								ADose dose = new ADose();
								dose.drugname = json.getString("drugname");
								dose.drugtype = json.getString("drugtype");
								dose.drugunit = json.getString("drugunit");
								dose.illness = json.getString("illness");
								Float f = new Float(json.getString("drugusage"));
								dose.drugusage = f.floatValue();
								doseList.add(dose);
							}
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private void updateViews(){
		if(reminder != null){
			reminderTime time = reminder.time;
			String timeString = String.valueOf(time.Hour) + ":" + String.valueOf(time.Min);
			reminderTime.setText(timeString);
			
			for(int i=0; i<7; i++){
				boolean isEnabled = false;
				if(((time.repeat >> i) & 0x01) == 1){
					isEnabled = true;
				}
				switch(i){
				case 0:{
					mMon.setActivated(isEnabled);
				}break;
				case 1:{
					mTue.setActivated(isEnabled);
				}break;
				case 2:{
					mWed.setActivated(isEnabled);
				}break;
				case 3:{
					mThur.setActivated(isEnabled);
				}break;
				case 4:{
					mFri.setActivated(isEnabled);
				}break;
				case 5:{
					mSat.setActivated(isEnabled);
				}break;
				case 6:{
					mSun.setActivated(isEnabled);
				}break;
				}
			}
			
			if(reminder.isopen == 1){
				mSwitchButton.setFlage(true);
			}else {
				mSwitchButton.setFlage(false);
			}
			
		}
		
		updateDoseList();
	}
	
	ADose dose = null;
	
	private void updateDoseList(){
		int size = doseList.size();
		mDoseList.removeAllViews();
		if(size > 0){
			LayoutInflater inflater = LayoutInflater.from(this);
			for(ADose d:doseList){
				View v = inflater.inflate(R.layout.health_drug_reminder_edit_item, null);
				RelativeLayout itemView = (RelativeLayout)v.findViewById(R.id.itemview);
				TextView mName = (TextView)v.findViewById(R.id.name);
				TextView mUnit = (TextView)v.findViewById(R.id.unit);
				ImageButton mDelete = (ImageButton)v.findViewById(R.id.delete);
				
				mName.setText(d.drugname);
				String unitString = String.valueOf(d.drugusage) + " " + d.drugunit;
				mUnit.setText(unitString);
				itemView.setTag(d);
				itemView.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						/*
						AlertDialog.Builder builder = new AlertDialog.Builder(HealthDrugReminderEdit.this);
						LayoutInflater factory = LayoutInflater.from(HealthDrugReminderEdit.this);
						View entryView = factory.inflate(R.layout.health_drug_list_item, null);
						builder.setView(entryView);
						NumberPicker typePicker = (NumberPicker)entryView.findViewById(R.id.drug_type_list);
						
						List<ADose> doseChooseList = mApp.getADoseFromChooseList();
						ADose tag = (ADose) v.getTag();
						ArrayList<String> typeAList = new ArrayList<>();
						int size = doseChooseList.size();
						int position = 0;
						if(size > 0){
							typeAList.clear();
							for(ADose d:doseChooseList){
								int j = 0;
								boolean add = true;
								for(String type:typeAList){
									add = false;
									if(d.drugtype.equalsIgnoreCase(type) == false){
										add = true;
									}
								}
								if(add){
									typeAList.add(d.drugtype);
								}
								if(d.drugtype.equalsIgnoreCase(tag.drugtype)){
									position = j;
								}
								j ++;
							}
						}
						String[] typeStrings = (String[]) typeAList.toArray(new String[0]);
						typePicker.setDisplayedValues(typeStrings);
						typePicker.setMaxValue(typeStrings.length - 1);
						typePicker.setMinValue(0);
						typePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
						typePicker.setValue(position);
						
						builder.create().show();
						*/
					}
				});
				mDelete.setTag(d);
				mDelete.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dose = (ADose) v.getTag();
						// TODO Auto-generated method stub
						mApp.showConfirmDialog(HealthDrugReminderEdit.this, getResources().getString(R.string.reminder_confirm_del_medicine), new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								if(v.getId() == R.id.alert_but1){
									doseList.remove(dose);
									updateDoseList();
									mApp.showAlertDialog(HealthDrugReminderEdit.this, getResources().getString(R.string.reminder_cmiok_del_medicine), R.string.ok, null);
								}
							}
						});
						
					}
				});
				
				mDoseList.addView(v);
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.drug_add_but:{
			
		}break;
		
		case R.id.time:{
			reminderTime time = reminder.time;
			TimePickerDialog timePicker = new TimePickerDialog(this, new OnTimeSetListener() {
				
				@Override
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					// TODO Auto-generated method stub
					reminder.time.Hour = hourOfDay;
					reminder.time.Min = minute;
					String timeString = String.valueOf(hourOfDay) + ":" + String.valueOf(minute);
					reminderTime.setText(timeString);
				}
			}, time.Hour, time.Min, true);
			timePicker.show();
		}break;
		
		case R.id.but_mon:{
			if(mMon.isActivated() == true){
				reminder.time.repeat &= ~0x01;
				mMon.setActivated(false);
			}else {
				reminder.time.repeat |= 0x01;
				mMon.setActivated(true);
			}
		}break;
		
		case R.id.but_tue:{
			if(mTue.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 1);
				mTue.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 1);
				mTue.setActivated(true);
			}
		}break;
		
		case R.id.but_wed:{
			if(mWed.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 2);
				mWed.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 2);
				mWed.setActivated(true);
			}
		}break;
		
		case R.id.but_thur:{
			if(mThur.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 3);
				mThur.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 4);
				mThur.setActivated(true);
			}
		}break;
		
		case R.id.but_fri:{
			if(mFri.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 4);
				mFri.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 4);
				mFri.setActivated(true);
			}
		}break;
		
		case R.id.but_sat:{
			if(mSat.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 5);
				mSat.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 5);
				mSat.setActivated(true);
			}
		}break;
		
		case R.id.but_sun:{
			if(mSun.isActivated() == true){
				reminder.time.repeat &= ~(0x01 << 6);
				mSun.setActivated(false);
			}else {
				reminder.time.repeat |= (0x01 << 6);
				mSun.setActivated(true);
			}
		}break;
		
		case R.id.but_commit:{
			
		}break;
		
		}
	}

}
